﻿using Kaskelot.SP.Core;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.WebPartPages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls.WebParts;

namespace Kaskelot.SP.Services
{
    public class PageService : IDisposable
    {
        private PublishingWeb pWeb;
        private SPWeb web;
        private PageLayoutCollection avaliableLayouts;

        public PageService(SPWeb web)
        {
            this.web = web;
            web.AllowUnsafeUpdates = true;
            pWeb = PublishingWeb.GetPublishingWeb(web);
            PublishingSite pSite = new PublishingSite(web.Site);
            avaliableLayouts = pSite.PageLayouts;
        }

        public void CreatePage(string urlName, string title, string pageLayout)
        {
            Logger.LogVerbose(this, LayerNames.Services, "CreatePage", "About to create page " + urlName + " with title " + title + " and pagelayout " + pageLayout);

            SPFile file = pWeb.Web.GetFile(pWeb.PagesList.RootFolder.ServerRelativeUrl + "/" + urlName);
            if (file.Exists)
            {
                Logger.LogVerbose(this, LayerNames.Services, "CreatePage", "Page already exists, skipping.");
                return;
            }

            PageLayout layout = avaliableLayouts.First(pl => pl.Name == pageLayout);
            urlName = urlName.EndsWith(".aspx") ? urlName : urlName + ".aspx";

            PublishingPage page = pWeb.AddPublishingPage(urlName, layout);

            page.Title = title;
            page.Update();

            page.ListItem.File.CheckIn("System checkin");
            page.ListItem.File.Publish("System publish");
        }

        public void SetDefaultPage(string pageName)
        {
            SPFile page = pWeb.PagesList.RootFolder.Files.Cast<SPFile>().FirstOrDefault(f => f.Name.ToLower() == pageName.ToLower());
            if (page != null)
            {
                pWeb.DefaultPage = page;
                pWeb.Update();
            }
        }

        public void AddWebPart(string pageName, System.Web.UI.WebControls.WebParts.WebPart wp, string zone, int index)
        {
            SPFile page = null;
            try
            {
                string pageUrl = PublishingWeb.GetPagesListName(web) + "/" + pageName;
                page = web.GetFile(pageUrl);
                if (page.Exists)
                {
                    page.CheckOut();
                    using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared))
                    {
                        wp.ChromeType = PartChromeType.None;
                        manager.AddWebPart(wp, zone, index);
                    }
                }
            }
            finally
            {
                if (page.Exists)
                    page.CheckIn("WebPart added", SPCheckinType.MajorCheckIn);
            }
        }

        public void DeleteAllWebParts(string pageName)
        {
            SPFile page = null;
            try
            {
                string pageUrl = PublishingWeb.GetPagesListName(web) + "/" + pageName;
                page = web.GetFile(pageUrl);
                if (page.Exists)
                {
                    page.CheckOut();
                    using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared))
                    {
                        System.Web.UI.WebControls.WebParts.WebPart[] wplist = new System.Web.UI.WebControls.WebParts.WebPart[manager.WebParts.Count];
                        manager.WebParts.CopyTo(wplist, 0);

                        foreach (System.Web.UI.WebControls.WebParts.WebPart wp in wplist)
                        {
                            manager.DeleteWebPart(wp);
                        }
                    }
                }
            }
            finally
            {
                if (page.Exists)
                    page.CheckIn("WebParts cleared", SPCheckinType.MajorCheckIn);
            }
        }

        public void Dispose()
        {
        }
    }
}
